﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.Web;

namespace Story.Library
{
    public class ReflectionHelper
    {

        /// <summary>
        /// 根据如下字符串格式来创建类型的实例 
        /// </summary>
        /// <param name="typeInfoStr">TypeFullName,AssemblyName 的字符串</param>
        /// <returns>一个类型的实例</returns>
        public static object CreateType(string typeInfoStr)
        {
            string typeName = typeInfoStr.Split(',')[0].Trim();
            string assemblyName = ReflectionHelper.ExecutingPath + typeInfoStr.Split(',')[1].Trim() + ".dll";
            Assembly assembly = Assembly.LoadFrom(assemblyName);
            return assembly.CreateInstance(typeName);
        }

        /// <summary>
        /// 根据如下字符串格式来创建类型的实例，并传入构造函数的参数
        /// </summary>
        /// <param name="typeInfoStr">TypeFullName,AssemblyName 的字符串</param>
        /// <param name="args">参数数组</param>
        /// <returns>一个类型的实例</returns>
        public static object CreateType(string typeInfoStr, object[] args)
        {
            string typeName = typeInfoStr.Split(',')[0].Trim();
            string assemblyName = ReflectionHelper.ExecutingPath + typeInfoStr.Split(',')[1].Trim() + ".dll";
            Assembly assembly = Assembly.LoadFrom(assemblyName);
            return Activator.CreateInstance(assembly.GetType(typeName), args);
        }

        /// <summary>
        /// 当前AppDomain的Assembly所在的文件夹
        /// 在Win下返回如c:\Storys\
        /// 在Web下返回如c:\Storys\appserver\bin\
        /// </summary>
        public static string ExecutingPath
        {
            get
            {
                if (HttpContext.Current == null)
                    return AppDomain.CurrentDomain.BaseDirectory + @"\";
                else
                    return AppDomain.CurrentDomain.RelativeSearchPath + @"\";
            }
        }
    }
}
